<link href="./css/style.css" rel="stylesheet" type="text/css" />
<link href="./css/DateTimePicker.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" charset="utf-8" src="/inc/Editer/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="/inc/Editer/ueditor.all.min.js"> </script>
<script type="text/javascript" charset="utf-8" src="/inc/Editer/lang/zh-cn/zh-cn.js"></script>
<script src="./js/jquery.js"></script>
<script src="./js/DateTimePicker.js"></script>
<script src="/skin/js/vue.js"></script>
<div class="main" style="height:auto;">
<div class="goods">
	<p class="tt"><a>首页</a>><a href="goodslist.php">商品管理</a>><span>添加商品</span></p>	
	<form class="goodadd">
		<div id='tab1' class='hide'>
			<p class="p1"><span>商品分类</span>
				<select name="cat" class="cat">
					<option value='2'>{$catarr[2]}</option><option value='3'>{$catarr[3]}</option>
				</select>
				<select name='cat1' class='cat1'>
				{loop $cat $key as $list}
					<option value="{$list[Id]}">{$list[name]}</option>
				{/loop}
				</select>
			</p>
			<p class="p1"><span>商品名称</span><input type="text" name="t0" placeholder="请输入商品名称" /></p>	
			<p class="p3"><span>市场价格</span><input type="text" name="yprice" placeholder="请输入商品市场价格" /></p>		
			<p class="p3"><span>会员价格</span><input type="text" name="cash" placeholder="请输入商品价格" /></p>
			
			<div class="zh">
				<p class="p3"><span>置换类型</span>
					<select name="type">
						<option value="0">-请选择-</option>
						<option value="1">单品</option>
						<option value="2">礼包</option>
					</select>
				</p>
			</div>
			<div class="gn">
				<p class="p3"><span>功能</span>
					<select name="tag1">
						<option value="0">-请选择-</option>
						{loop $taglist1 $key as $list}
						<option value="{$list[Id]}">{$list[name]}</option>
						{/loop}
					</select>
				</p>
			</div>
			<div class="gn">
				<p class="p3"><span>材质</span>
					<select name="tag2">
						<option value="0">-请选择-</option>
						{loop $taglist2 $key as $list}
						<option value="{$list[Id]}">{$list[name]}</option>
						{/loop}
					</select>
				</p>
			</div>
			<p class="p3 zh"><span>置换费</span><input type="text" name="kdf" placeholder="置换费" /></p>
			<p class="p3"><span>库存</span><input type="text" name="t9" placeholder="库存为0自动下架" /></p>			
			<p class="p3"><span>销量</span><input type="text" name="t10" placeholder="销量" /></p>
			<p class="p3"><span>排序</span><input type="text" name="t12" placeholder="数字越大越靠前" /></p>
			<div id='tab3' class='hide uppic' style="height:120px;">	
				<span>缩略图</span>
				<div class="gerenUpload" style="width:120px; height:105px; border:1px solid #ddd;position: relative; margin-right:20px;">
					<input type="file" id="upload" name="" data-name="1" class="sc" />
					<input type="hidden" id="img1" name="img[]" />
					<img src="/skin/img/mr.png" alt="" id="moren1">
					<a class='del' style='cursor:pointer; position:absolute; z-index:999; top:0; right:0; width:20px; height:20px; line-height:20px; text-align:center; border-left:1px solid #ddd; border-bottom:1px solid #ddd;background:red; color:#fff; '>X</a>
				</div>		
				<div class="gerenUploadMore"  >
	
				</div>
				<div style="clear:both;"></div>		
			</div>
			<div class="p2"><span class="sx">内容</span><script id="editor" type="text/plain" style="width:800px;height:300px;"></script></div>
			<button type="button" onclick="goodadd();">确认添加</button>
		</div>		
				
	</form>	
	<script>
	
	$(".cat").change(function(){
		lx = $(".cat option:selected").val();
		$(".gn,.zh").hide();
		if(lx==2){		
			$(".gn,.zh").show();
		}
		$.ajax({
			type:"post",
			dataType:"json",
			url:"/Moudel.php?m=g&a=cat",
			data:"id="+lx,
			success:function(d){
				if(d[0]==0){
					$(".cat1").hide();
				}else{
					$(".cat1").show();
					$(".cat1").html(d[1]);
				}
			}
		});
	});
	$(".uppic").delegate(".del","click",function (e) {
		$(this).parent().remove();
		$(".gerenUploadMore").show();
	});
	$(".gerenUploadMore").click(function () {
		let i = $(".gerenUpload").length + 1;
		$(this).before(`<div class="gerenUpload" style="width:120px; height:105px; border:1px solid #ddd;position: relative; margin-right:20px;">
	\t\t\t\t\t<input type="file" id="upload" name="" data-name="${i}" class="sc" />
	\t\t\t\t\t<input type="hidden" id="img${i}" name="img[]" />
	\t\t\t\t\t<img src="/skin/img/mr.png" alt="" id="moren${i}">
	\t\t\t\t\t<a class='del' style='cursor:pointer; position:absolute; z-index:999; top:0; right:0; width:20px; height:20px; line-height:20px; text-align:center; border-left:1px solid #ddd; border-bottom:1px solid #ddd;background:red; color:#fff; '>X</a>
	\t\t\t\t</div>`)
		if (i == 5) {
			$(this).hide();
		}
	});
			
	
	var ue = UE.getEditor('editor');	
	function goodadd(){
		var data = $("#hide").html();
			$.ajax({
				type:"post",
				dataType:"json",
				url:"/Moudel.php?m=g&a=goodadd",
				data:$(".goodadd").serialize()+"&data="+data,
				success:function(d){
					if(d[0]==0){
						alert(d[1]);
					}
					else{
						alert(d[1]);
						window.location.href='goodslist.php';
					}
				}
			});
		}
	
	const ACCEPT = ['image/jpg', 'image/png', 'image/jpeg'];
    const MAXSIZE = 1024 * 1024 * 2;
    const MAXSIZE_STR = '2MB';

    function convertImageToBase64(file,callback) {
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.addEventListener('load', function(e){
        const base64Image = e.target.result;
        callback && callback(base64Image);
        reader = null;
      })
    }
    // 图片压缩
    function compress(base64Image,callback){
      let maxW = 640;
      let maxH = 640;
      const image = new Image();
      image.addEventListener('load', function(e){
        let ratio; //图片的压缩比
        let needCompress = false; // 是否需要压缩
        if(maxW < image.naturalWidth) {
          needCompress = true;
          ratio = image.naturalWidth / maxW;
          maxH = image.naturalHeight / ratio;
        }
        //经过处理后，实际图片的尺寸为1024 * 640;
        if(maxH < image.naturalHeight) {
          needCompress = true;
          ratio = image.naturalHeight / maxH;
          maxW = image.naturalWidth / ratio;
        }
        if(!compress) {
          maxW = image.naturalWidth;
          maxH = image.naturalHeight;
        }//如果不需要压缩，需要获取图片的实际尺寸

        const canvas = document.createElement('canvas');
        canvas.setAttribute('id','__compress__');
        canvas.width = maxW;
        canvas.height = maxH;
        canvas.style.visibility = 'hidden';
        // document.body.appendChild(canvas);

        const ctx = canvas.getContext('2d');
        ctx.clearRect(0,0,maxW,maxH);
        ctx.drawImage(image, 0, 0, maxW, maxH);
        // toDataURL的第二个参数表示图片质量，取值为0-1 1为原图
        const compressImage = canvas.toDataURL('image/jpeg', 0.5);
        callback && callback(compressImage);

        //在页面上展示压缩后的图片
      });
      image.src = base64Image;
      // document.body.appendChild(image);

    }
    //获得压缩后的base64
    function uploadToServer(compressImage) {
      //这里调用上传图片base64编码的接口
      compressImage = encodeURIComponent(compressImage);
      $.ajax({
        type:"post",
        dataType:"json",
        url:"/Moudel.php?m=g&a=upload",
        data:"img="+compressImage,
        success:function(d){
          if(d[0]==0){
            alert(d[1]);
          }
          else{           
			pare.children("input[type=hidden]").attr('value',d[1]);
			pare.children("img").attr('src',d[1]);
          }
        }
      });
    }

    const upload = document.getElementById('upload');
	var uploadS = document.getElementsByClassName("sc");

	$(".uppic").delegate(".sc","click",function (e) {
		var changeExed = false;
		pare = $(this).parent(".gerenUpload");
		
		$(this).change(function (e) {
			if (!changeExed) {
				changeExed = true;
				type = 1;
				const [file] = e.target.files;
				if(!file) {
					return;
				}
				const { type: fileType, size: fileSize } = file;
				//图片支持类型检查
				if(!ACCEPT.includes(fileType)) {
					alert(`不支持[${fileType}]文件类型!`);
					upload.value = '';
					return;
				}
				//图片容量检查
				if(fileSize > MAXSIZE) {
					alert(`文件大小超出${MAXSIZE_STR}!`);
					upload.value = '';
					return;
				}
				//压缩图片
				
				convertImageToBase64(file, (base64Image) => compress(base64Image,uploadToServer));
			}
		});
	});

	</script>
	
</div>
</div>